package com.kexio.security.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kexio.common.dto.PageRequest;
import com.kexio.security.domain.Role;
import com.kexio.security.service.RoleRepository;
import com.kexio.security.mapper.RoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 角色数据访问实现类
 * 
 * @author kexio
 */
@Repository
public class RoleRepositoryImpl implements RoleRepository {

    private static final Logger log = LoggerFactory.getLogger(RoleRepositoryImpl.class);

    private final RoleMapper roleMapper;

    public RoleRepositoryImpl(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Override
    public Role save(Role role) {
        if (role.getId() == null) {
            // 新增角色
            role.setCreatedTime(LocalDateTime.now());
            role.setUpdatedTime(LocalDateTime.now());
            roleMapper.insert(role);
            log.debug("角色新增成功: {}", role.getRoleName());
        } else {
            // 更新角色
            role.setUpdatedTime(LocalDateTime.now());
            roleMapper.updateById(role);
            log.debug("角色更新成功: {}", role.getRoleName());
        }
        return role;
    }

    @Override
    public Optional<Role> findById(Long id) {
        Role role = roleMapper.selectById(id);
        return Optional.ofNullable(role);
    }

    @Override
    public Optional<Role> findByRoleCode(String roleCode) {
        Role role = roleMapper.findByRoleCode(roleCode);
        return Optional.ofNullable(role);
    }

    @Override
    public Optional<Role> findByRoleName(String roleName) {
        Role role = roleMapper.findByRoleName(roleName);
        return Optional.ofNullable(role);
    }

    @Override
    public boolean existsByRoleCode(String roleCode, Long excludeId) {
        long count = roleMapper.countByRoleCode(roleCode, excludeId);
        return count > 0;
    }

    @Override
    public boolean existsByRoleName(String roleName, Long excludeId) {
        long count = roleMapper.countByRoleName(roleName, excludeId);
        return count > 0;
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.selectList(null);
    }

    @Override
    public com.kexio.common.dto.PageResponse<Role> findPage(String roleName, Integer status, PageRequest pageRequest) {
        // 创建MyBatis-Plus分页对象
        Page<Role> mpPage = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        
        // 执行分页查询
        IPage<Role> result = roleMapper.selectRolePage(mpPage, roleName, status);
        
        // 转换为通用分页对象
        com.kexio.common.dto.PageResponse<Role> pageResponse = new com.kexio.common.dto.PageResponse<>(
            result.getRecords(),
            (int) result.getCurrent(),
            (int) result.getSize(),
            result.getTotal()
        );
        
        log.debug("分页查询角色完成，共{}条记录", result.getTotal());
        return pageResponse;
    }

    @Override
    public List<Role> findByStatus(Integer status) {
        return roleMapper.selectByStatus(status);
    }

    @Override
    public List<Role> findByRoleType(Integer roleType) {
        return roleMapper.selectByRoleType(roleType);
    }

    @Override
    public List<Role> findByUserId(Long userId) {
        return roleMapper.selectByUserId(userId);
    }

    @Override
    public int deleteById(Long id) {
        int rows = roleMapper.deleteById(id);
        log.debug("删除角色{}，影响{}行", id, rows);
        return rows;
    }

    @Override
    public int deleteByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        int rows = roleMapper.deleteByIds(ids);
        log.debug("批量删除角色{}个，影响{}行", ids.size(), rows);
        return rows;
    }

    @Override
    public long count() {
        Long count = roleMapper.selectCount(null);
        return count != null ? count : 0L;
    }
}
